<template>
  <div>
    <!-- -------------------------给用户授权---------------------------- -->
    <el-dialog
      title="角色授权"
      :visible.sync="assingPermissionVisible"
      style="height=30%"
    >
      <el-tree
        :data="treedata"
        show-checkbox
        check-strictly="true"
        node-key="id"
        ref="tree"
        default-expand-all
        :default-checked-keys="checkedkeys"
        :props="defaultProps"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assingPermissionVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePermission">确 定</el-button>
      </span>
    </el-dialog>
    <!-- ----------------表格---------------------- -->
    <el-table :data="roleList" border style="width: 100%; line-height: 0%">
      <el-table-column prop="id" label="编号" width="180"> </el-table-column>
      <el-table-column prop="roleName" label="角色名称" width="180">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="danger"
            size="mini"
            @click="assignPermission(scope.row.id)"
            >分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rid:"",
      assingPermissionVisible: false,
      roleList: [], //角色列表
      treedata: [], //树节点数据
      checkedkeys: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  methods: {
    // 修改角色的权限
    savePermission() {
      let checkedNodes = this.$refs.tree.getCheckedKeys();
      this.$axios
        .put("/auth-serv/permissions/savePers", {
          rid: this.rid,
          pids: checkedNodes,
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.success("授权成功");
            this.assingPermissionVisible = false;
          }
        })
        .catch((error) => {
          this.$message.error("出错了");
        });
    },
    // 得到所有的角色列表
    loadRoles() {
      this.$axios.get("/auth-serv/roles/getAllRoles").then((res) => {
        this.roleList = res.data.data.roleList;
      });
    },
    // 得到所有的权限列表以及角色对应的权限
    assignPermission(rid) {
      this.rid=rid;
      this.$axios
        .get("/auth-serv/roles/persTree/" + rid)
        .then((res) => {
          if (res.data.code == 200) {
            this.treedata = res.data.data.treeList;
            this.checkedkeys = res.data.data.checkedkeys;
            this.assingPermissionVisible = true;
          }
        })
        .catch((error) => {
          this.$message.error("出错了");
        });
    },
  },
  mounted() {
    this.loadRoles();
  },
};
</script>
